<template>
  <!-- <doc-alert title="用户体系" url="https://doc.iocoder.cn/user-center/" /> -->
  <!-- <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" /> -->
  <!-- <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" /> -->

  <el-row :gutter="24">
    <!-- 左侧部门树 -->
    <!-- <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col> -->
    <el-col :span="24" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="auto"
          label-position="right"
        >
          <!-- <el-form-item :label="t('page_sys.user.labelSszz')" prop="deptId">
            <el-tree-select
              v-model="queryParams.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              :placeholder="t('page_sys.user.placeholderSszz')"
              class="!w-240px"
            />
          </el-form-item> -->
          <el-form-item :label="t('page_sys.user.labelSjh')" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              :placeholder="t('page_sys.user.placeholderSjh')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item :label="t('page_sys.user.labelYhzh')" prop="username">
            <el-input
              v-model="queryParams.username"
              :placeholder="t('page_sys.user.placeholderYhzz')"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item :label="t('page_sys.user.labelRole')" prop="username">
            <el-select
              v-model="queryParams.roleId"
              :placeholder="t('page_sys.user.placeholderRole')"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in roleList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('page_sys.user.labelState')" prop="status">
            <el-select
              v-model="queryParams.status"
              :placeholder="t('page_sys.user.labelUserState')"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" v-hasPermi="['system:user:query']">
              <Icon icon="ep:search" />{{ t('action.search') }}
            </el-button>
            <el-button @click="resetQuery" v-hasPermi="['system:user:query']">
              <Icon icon="ep:refresh" />{{ t('action.reset') }}
            </el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:plus" /> {{ t('page_sys.user.labelCreateUser') }}
            </el-button>
            <!-- <el-button
              type="primary"
              plain
              @click="syncUserFromBms()"
              v-hasPermi="['system:user:create']"
            >
              <Icon icon="ep:refresh" />{{ t('page_sys.user.labelSyncUser') }}
            </el-button> -->
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list">
          <!-- <el-table-column label="用户编号" align="center" key="id" prop="id" /> -->
          <el-table-column
            :label="t('page_sys.user.labelNickname')"
            align="center"
            prop="nickname"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('page_sys.user.labelYhzh')"
            align="center"
            prop="username"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="t('page_sys.user.labelSjh')"
            align="center"
            prop="mobile"
            width="120"
          />
          <el-table-column
            :label="t('page_sys.user.labelSex')"
            align="center"
            prop="sex"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">{{
                scope.row.sex == 1 ? '男' : scope.row.sex == 2 ? '女' : '-'
              }}</template></el-table-column
          >
          <el-table-column label="用户角色" align="center" key="userRoles" prop="userRoles">
            <template #default="scope">{{
                scope.row.userRoles?.map((item) => item.roleName).join(', ')
              }}</template>
          </el-table-column>
          <el-table-column :label="t('page_sys.user.labelState')" key="status">
            <template #default="scope">
              <dict-tag
                v-if="checkPermi(['system:user:update'])"
                :type="DICT_TYPE.COMMON_STATUS"
                :value="scope.row.status"
              />
              <!-- bug-fixed -->
              <!-- 如果没编辑权限，要能看到权限 -->
              <span v-else style="padding-left: 5px; padding-top: 2px">{{
                  scope.row.status == 0
                    ? t('page_sys.user.labelStateEnable')
                    : t('page_sys.user.labelStateDisable')
                }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="t('table.createTime')"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
          <el-table-column :label="t('table.action')" align="center" width="160">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                >
                  编辑
                </el-button>
                <!-- <el-button type="primary" link> 取消关联 </el-button> -->
                <el-button type="primary" link @click="handleStatusChange(scope.row)">
                  {{ scope.row.status !== CommonStatusEnum.ENABLE ? '启用' : '冻结' }}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 用户导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useRoute } from 'vue-router'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import UserForm from './UserForm.vue'
import UserImportForm from './UserImportForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
// import DeptTree from './DeptTree.vue'
import * as DeptApi from '@/api/system/dept'
import * as RoleApi from '@/api/system/role'
import { defaultProps, handleTree } from '@/utils/tree'
defineOptions({ name: 'SystemUser' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const roleList = ref<RoleApi.RoleVO[]>([])
const deptList = ref<Tree[]>([]) // 树形结构
const route = useRoute()

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined,
  roleId: undefined
})
const queryFormRef = ref() // 搜索的表单

const checkTenantAdmin = (row: any) => {
  const roleStrArr = row?.userRoles?.map((i) => i.code)
  return roleStrArr?.includes('tenant-admin')
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getNewUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.roleId = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/* 同步用户 */
const syncUserFromBms = async () => {
  loading.value = true
  try {
    const data = await UserApi.syncUserFromBmsApi()
    // console.log('data :>> ', data);
    message.success(data.msg || t('common.SyncSucess'))
  } finally {
    loading.value = false
  }
}
/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 查询角色列表 */
const getRoleList = async () => {
  loading.value = true
  try {
    const data = await RoleApi.getSimpleRoleList()
    roleList.value = data
  } finally {
    loading.value = false
  }
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text =
      row.status !== CommonStatusEnum.ENABLE
        ? t('page_sys.user.labelStateEnable')
        : t('page_sys.user.labelStateClose')
    await message.confirm(
      t('page_sys.user.labelStateSurePre') +
      text +
      '"' +
      row.nickname+row.username +
      '"' +
      t('page_sys.user.labelStateSureAppend')
    )
    // 发起修改状态
    try {
      const result = await UserApi.updateUserStatus(row.id, row.status == 0 ? 1 : 0)
      // 刷新列表
      await getList()
    } catch (e) {
      if (e && e?.code == 1002029000) {
        await message.confirm(e.msg)
        // 强制删除
        handleStatusChangeForce(row)
      } else {
        message.error(e.msg || t('common.fail'))
      }
    }
  } catch {
    // // 取消后，进行恢复按钮
    // row.status =
    //   row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}


const handleStatusChangeForce = async (row: UserApi.UserVO) => {
  try {
    // 强制关闭
    row.force = true
    const result = await UserApi.updateUserStatus(row.id, 1)
    console.log('result :>> ', result)
    // 刷新列表
    await getList()
  } catch (e) {}
}
/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await UserApi.exportUser(queryParams)
    download.excel(data, t('page_sys.user.titleYhlb') + '.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    await message.confirm('确定要重置密码吗？')
    // // 重置的二次确认
    // const result = await message.prompt(
    //   t('page_sys.user.labelPwdPre') + '"' + row.username + '"' + t('page_sys.user.labelPwdAppend'),
    //   t('common.reminder')
    // )
    // const password = result.value
    // const hasSpecialChars =
    //   /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{6,16}$/.test(
    //     password
    //   )
    // if (!hasSpecialChars) {
    //   message.error(t('page_sys.user.tipPwdError'))
    //   return false
    // }

    // 发起重置
    await UserApi.resetUserPwd(row.id)
    message.success(t('page_sys.user.labelPwdResetSuc'))
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

/** 初始化 */
onMounted(async () => {
  if (route.query.roleId) {
    queryParams.roleId = Number(route.query.roleId)
  }
  getRoleList()
  getList()
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
})
</script>
